<?php

namespace lvzmen\YiiGoogleConsole\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use lvzmen\YiiGoogleConsole\models\LoginForm;

/**
 * Site controller
 */
class LoginController extends Controller
{
    public $layout = "@vendor/lvzmen/yii-google-console/layout/main";

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'login', 'index'],
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }


    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('@vendor/lvzmen/yii-google-console/views/index');
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }

        $model->password = '';

        $this->layout = false;
        return $this->render('@vendor/lvzmen/yii-google-console/views/login', [
            'model' => $model,
        ]);
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        $this->layout = false;

        Yii::$app->user->logout();

        return $this->goHome();
    }

}
